﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace serial
{


    public partial class MainForm : Form
    {
        WaveForm waveForm;
 
        public MainForm()
        {
            InitializeComponent();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 端口检查
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbPort_Click(object sender, EventArgs e)
        {
            RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm");
            if (keyCom != null)
            {
                string[] sSubKeys = keyCom.GetValueNames();
                cbPort.Items.Clear();
                foreach (string name in sSubKeys)
                {
                    string sValue = (string)keyCom.GetValue(name);
                    cbPort.Items.Add(sValue);
                }
                if (cbPort.Items.Count > 0)
                    cbPort.SelectedIndex = 0;
            }
            cbBaud.Text = "115200";
        }

        bool isOpened = false;//串口当前打开状态
        private void button1_Click(object sender, EventArgs e)
        {
            if (!isOpened)
            {
                try
                {
                    serialPort1.PortName = cbPort.Text;
                    serialPort1.BaudRate = Convert.ToInt32(cbBaud.Text);
                    try
                    {   //打开串口
                        serialPort1.Open(); 
                        button1.Text = "关闭串口";
                        cbPort.Enabled = false;
                        cbBaud.Enabled = false;
                        isOpened = true;
                        serialPort1.DataReceived += new SerialDataReceivedEventHandler(post_DataReceived); //串口接收处理
                        Console.WriteLine("hello");
                    }

                    catch
                    {
                        MessageBox.Show("串口打开失败！", "提示");
                    }
                }
                catch
                {
                    MessageBox.Show("选好你的串口号和波特率啊傻逼崽", "你是傻的吗？");
                }

            }
            else
            {
                try
                {   // 关闭串口
                    serialPort1.Close();
                    button1.Text = "打开串口";
                    cbPort.Enabled = true;
                    cbBaud.Enabled = true;
                    isOpened = false;
                    if(th!=null)
                    th.Abort();
                    //hx = true;
                }
                catch
                {
                    MessageBox.Show("串口打开失败！", "提示");
                }
            }
        }

        
        bool hx = true;
        Thread th;
        private void post_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int len = serialPort1.BytesToRead;
            Console.WriteLine(serialPort1.BytesToRead);
            protocol.Serialdata = new byte[len];

            if (!rdproReceive.Checked)
            {
                if (!cbShowHex.Checked)
                {
                    string str = serialPort1.ReadExisting();//字符串方式读取
                    //tbReceive.BeginInvoke(new Action<string>(s => { tbReceive.AppendText(s); }), str); //这里使用异步会导致UI假死 2019.8.6
                    tbReceive.Invoke(new Action<string>(s => { tbReceive.AppendText(s); }), str);
                }
                else
                {//十六进制
                    serialPort1.Read(protocol.Serialdata, 0, len);
                    for (int i = 0; i < len - 1; i++)
                    {
                        //tbReceive.BeginInvoke(new Action<string>(s => { tbReceive.AppendText(s); }), protocol.Serialdata[i].ToString("X2") + "  ");//这里使用异步会导致UI假死 2019.8.6
                        tbReceive.Invoke(new Action<string>(s => { tbReceive.AppendText(s); }), protocol.Serialdata[i].ToString("X2") + "  ");
                    }
                   
                }
            }
            else
            {
                serialPort1.Read(protocol.Serialdata, 0, len);
                if (hx)//暂时用
                {
                    //开一个线程专门校验分类数据
                    th = new Thread(protocol.CheckData);
                    th.IsBackground = true;
                    th.Start();
                    hx = false;
                }

            }

        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            byte[] buffer;
            //发送数据
            if (serialPort1.IsOpen)
            {
                //如果串口开启
                if (tbSend.Text.Trim() != "")
                {
                    if (!chBoxSendHex.Checked)
                    {
                        buffer = sendByte(tbSend.Text);
                        serialPort1.Write(buffer, 0, buffer.Length);
                        buffer = null;
                    }
                    else
                        sendHexByte(tbSend.Text);
                }
                else
                {
                    MessageBox.Show("不写东西你让我发个锤子啊？", "发送失败");
                }
            }
            else
            {
                MessageBox.Show("串口没打开", "提示");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            tbReceive.Text = "";


            //protocol.ForwardThrottle = 100;
            //protocol.TransverseThrottle = 101;
            //protocol.VerticalThorttle = 102;
            //protocol.LightPwm = 103;
            //protocol.Ptz = 104;
            //protocol.Steering = 105;

            //serialPort1.Write(protocol.MoveControlData(), 0, protocol.MoveControlData().Length);

        }

        private byte[] sendByte(string str)
        {
            byte[] arr = Encoding.Default.GetBytes(str);
            return arr;
        }

        private byte[] sendHexByte(string hexstr)
        {
            hexstr = hexstr.Replace(" ", "");
            if ((hexstr.Length % 2) != 0)
                hexstr += " ";
            byte[] hexbyte = new byte[hexstr.Length / 2];
            for (int i = 0; i < hexbyte.Length; i++)
            {
                hexbyte[i] = Convert.ToByte(hexstr.Substring(i * 2, 2), 16);
            }
            return hexbyte;
        }

        szyProtocol protocol = new szyProtocol();
        private void BtnShowWare_Click(object sender, EventArgs e)
        {
            if (waveForm == null)
            {
                waveForm = new WaveForm();
                waveForm.Show();
            }
            else
            {
                if (waveForm.IsDisposed)
                {
                    waveForm = new WaveForm();
                    waveForm.Show();
                }
            }
        }

        private void TabControl1_DrawItem(object sender, DrawItemEventArgs e)
        {
            Rectangle tabArea = tabControl1.GetTabRect(e.Index);//主要是做个转换来获得TAB项的RECTANGELF 
            RectangleF tabTextArea = (RectangleF)(tabControl1.GetTabRect(e.Index));
            Graphics g = e.Graphics;
            StringFormat sf = new StringFormat();//封装文本布局信息 
            sf.LineAlignment = StringAlignment.Center;
            sf.Alignment = StringAlignment.Center;
            Font font = this.tabControl1.Font;
            SolidBrush brush = new SolidBrush(Color.Black);//绘制边框的画笔 
            g.DrawString(((TabControl)(sender)).TabPages[e.Index].Text, font, brush, tabTextArea, sf);
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            //保持只有300行
            if (tbReceive.Lines.Length > 300)
            {
                string[] newline = new string[300];
                Array.Copy(this.tbReceive.Lines, this.tbReceive.Lines.Length - 300, newline, 0, 300);
                this.tbReceive.Lines = newline;
            }
        }

        private void BtnChangePID_Click(object sender, EventArgs e)
        {
            if (btnChangePID.Text == "开启调试")
            {
                btnChangePID.Text = "关闭调试";
                tbPpitch.ReadOnly = false;
                tbProll.ReadOnly = false;
                tbPyaw.ReadOnly = false;
                tbIpitch.ReadOnly = false;
                tbIroll.ReadOnly = false;
                tbIyaw.ReadOnly = false;
                tbDpitch.ReadOnly = false;
                tbDroll.ReadOnly = false;
                tbDyaw.ReadOnly = false;
                tbPnum.ReadOnly = false;
                tbInum.ReadOnly = false;
                tbDnum.ReadOnly = false;

                tbPpitch.Text = Properties.Settings.Default.ppitch.ToString();
                tbProll.Text = Properties.Settings.Default.pproll.ToString();
                tbPyaw.Text = Properties.Settings.Default.ppyaw.ToString();
                tbIpitch.Text = Properties.Settings.Default.ipitch.ToString();
                tbIroll.Text = Properties.Settings.Default.iroll.ToString();
                tbIyaw.Text = Properties.Settings.Default.iyaw.ToString();
                tbDpitch.Text = Properties.Settings.Default.dpitch.ToString();
                tbDroll.Text = Properties.Settings.Default.droll.ToString();
                tbDyaw.Text = Properties.Settings.Default.dyaw.ToString();
                tbPnum.Text = Properties.Settings.Default.pnum.ToString();
                tbInum.Text = Properties.Settings.Default.inum.ToString();
                tbDnum.Text = Properties.Settings.Default.dnum.ToString();
            }
            else
            {
                btnChangePID.Text = "开启调试";
                tbPpitch.ReadOnly = true;
                tbProll.ReadOnly = true;
                tbPyaw.ReadOnly = true;
                tbIpitch.ReadOnly = true;
                tbIroll.ReadOnly = true;
                tbIyaw.ReadOnly = true;
                tbDpitch.ReadOnly = true;
                tbDroll.ReadOnly = true;
                tbDyaw.ReadOnly = true;
                tbPnum.ReadOnly = true;
                tbInum.ReadOnly = true;
                tbDnum.ReadOnly = true;
            }
        }

        private void BtnSendPID_Click(object sender, EventArgs e)
        {
            protocol.Ppitch1 = float.Parse(tbPpitch.Text);
            protocol.Proll1 = float.Parse(tbProll.Text);
            protocol.Pyaw1 = float.Parse(tbPyaw.Text);
            protocol.Ipitch1 = float.Parse(tbIpitch.Text);
            protocol.Iroll1 = float.Parse(tbIroll.Text);
            protocol.Iyaw1 = float.Parse(tbIyaw.Text);
            protocol.Dpitch1 = float.Parse(tbDpitch.Text);
            protocol.Droll1 = float.Parse(tbDroll.Text);
            protocol.Dyaw1 = float.Parse(tbDyaw.Text);

            //Console.WriteLine(protocol.Ppitch1);
            //Console.WriteLine(protocol.Proll1);
            //Console.WriteLine(protocol.Pyaw1);
            //Console.WriteLine(protocol.Ipitch1);
            //Console.WriteLine(protocol.Iroll1);
            //Console.WriteLine(protocol.Iyaw1);
            //Console.WriteLine(protocol.Dpitch1);
            //Console.WriteLine(protocol.Droll1);
            //Console.WriteLine(protocol.Dyaw1);
            serialPort1.Write(protocol.AdjustData(), 0, protocol.AdjustData().Length);

            Properties.Settings.Default.ppitch = float.Parse(tbPpitch.Text);
            Properties.Settings.Default.pproll = float.Parse(tbProll.Text);
            Properties.Settings.Default.ppyaw = float.Parse(tbPyaw.Text);
            Properties.Settings.Default.ipitch = float.Parse(tbIpitch.Text);
            Properties.Settings.Default.iroll = float.Parse(tbIroll.Text);
            Properties.Settings.Default.iyaw = float.Parse(tbIyaw.Text);
            Properties.Settings.Default.dpitch = float.Parse(tbDpitch.Text);
            Properties.Settings.Default.droll = float.Parse(tbDroll.Text);
            Properties.Settings.Default.dyaw = float.Parse(tbDyaw.Text);
            Properties.Settings.Default.Save();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(serialPort1.IsOpen)
            serialPort1.Close();
        }



        #region  调PID按键部分
        private void BtnppSub_Click(object sender, EventArgs e)
        {
            float x = float.Parse(tbPpitch.Text);
            tbPpitch.Text = (x -= Properties.Settings.Default.pnum).ToString();
        }

        private void BtnprSub_Click(object sender, EventArgs e)
        {
            float x = float.Parse(tbProll.Text);
            tbProll.Text = (x -= Properties.Settings.Default.pnum).ToString();
        }

        private void BtnpySub_Click(object sender, EventArgs e)
        {
            float x = float.Parse(tbPyaw.Text);
            tbPyaw.Text = (x -= Properties.Settings.Default.pnum).ToString();
        }

        private void BtnipSub_Click(object sender, EventArgs e)
        {
            float x = float.Parse(tbIpitch.Text);
            tbIpitch.Text = (x -= Properties.Settings.Default.inum).ToString();
        }

        private void BtnirSub_Click(object sender, EventArgs e)
        {
            float x = float.Parse(tbIroll.Text);
            tbIroll.Text = (x -= Properties.Settings.Default.inum).ToString();
        }

        private void BtniySub_Click(object sender, EventArgs e)
        {
            float x = float.Parse(tbIyaw.Text);
            tbIyaw.Text = (x -= Properties.Settings.Default.inum).ToString();
        }

        private void BtndpSub_Click(object sender, EventArgs e)
        {
            float x = float.Parse(tbDpitch.Text);
            tbDpitch.Text = (x -= Properties.Settings.Default.dnum).ToString();
        }

        private void BtndrSub_Click(object sender, EventArgs e)
        {
            float x = float.Parse(tbDroll.Text);
            tbDroll.Text = (x -= Properties.Settings.Default.dnum).ToString();
        }

        private void BtndySub_Click(object sender, EventArgs e)
        {
            float x = float.Parse(tbDyaw.Text);
            tbDyaw.Text = (x -= Properties.Settings.Default.dnum).ToString();
        }

        private void BtnprAdd_Click(object sender, EventArgs e)
        {
            float x = float.Parse(tbProll.Text);
            tbProll.Text = (x += Properties.Settings.Default.pnum).ToString();
        }

        private void BtnpyAdd_Click(object sender, EventArgs e)
        {
            float x = float.Parse(tbPyaw.Text);
            tbPyaw.Text = (x += Properties.Settings.Default.pnum).ToString();
        }

        private void BtnipAdd_Click(object sender, EventArgs e)
        {
            float x = float.Parse(tbIpitch.Text);
            tbIpitch.Text = (x += Properties.Settings.Default.inum).ToString();
        }

        private void BtnirAdd_Click(object sender, EventArgs e)
        {
            float x = float.Parse(tbIroll.Text);
            tbIroll.Text = (x += Properties.Settings.Default.inum).ToString();
        }

        private void BtniyAdd_Click(object sender, EventArgs e)
        {
            float x = float.Parse(tbIyaw.Text);
            tbIyaw.Text = (x += Properties.Settings.Default.inum).ToString();
        }

        private void BtndpAdd_Click(object sender, EventArgs e)
        {
            float x = float.Parse(tbDpitch.Text);
            tbDpitch.Text = (x += Properties.Settings.Default.dnum).ToString();
        }

        private void BtndrAdd_Click(object sender, EventArgs e)
        {
            float x = float.Parse(tbDroll.Text);
            tbDroll.Text = (x += Properties.Settings.Default.dnum).ToString();
        }

        private void BtndyAdd_Click(object sender, EventArgs e)
        {
            float x = float.Parse(tbDyaw.Text);
            tbDyaw.Text = (x += Properties.Settings.Default.dnum).ToString();
        }

        private void BtnppAdd_Click(object sender, EventArgs e)
        {
            float x = float.Parse(tbPpitch.Text);
            tbPpitch.Text = (x += Properties.Settings.Default.pnum).ToString();
        }

        private void BtnPconfirm_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.pnum = float.Parse(tbPnum.Text);
            Properties.Settings.Default.Save();
        }

        private void BtnIconfirm_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.inum = float.Parse(tbInum.Text);
            Properties.Settings.Default.Save();
        }

        private void BtnDconfirm_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.dnum = float.Parse(tbDnum.Text);
            Properties.Settings.Default.Save();
        }



        #endregion

        private void 协议ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            helper helper = new helper();
            helper.Show();
        }

        private void 帮助ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("暂时不想帮助你，自己解决谢谢","I'm terrible sorry!");
        }
    }
}



